package one.stand.service.impl;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import one.stand.model.*;
import one.stand.request.AssembleRequest;
import one.stand.request.GoodSpecRequest;
import one.stand.request.GoodsAssembleRequest;
import one.stand.response.AssembleResponse;
import one.stand.response.GoodsAssembleResponse;
import one.stand.service.AssembleService;
import one.stand.service.BaseService;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

/**
 * @author Administrator
 */
@Service
@Transactional
public class AssembleServiceImpl extends BaseService implements AssembleService {

    private boolean isNumber(String s) {
        if (StringUtils.isEmpty(s)) {
            return false;
        }
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (!Character.isDigit(c)) {
                return false;
            }
        }
        return true;
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public ResultModel<Boolean> insertGoodsAssemble(GoodsAssembleRequest request) {
        SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
        if (request == null || request.getGoodsId() == null || request.getAssembleType() == null) {
            return ResultModel.checkParamFail("goodsId为空或者assembleType为空");
        }
        if (request.getStartTimes() == null || request.getEndTimes() == null) {
            return ResultModel.fail("请输入开团时间和结束时间~！");
        }
        if (request.getUpdateType() == null) {
            return ResultModel.fail("请传入UpdateType~！");
        }
        // 草稿箱修改时 不校验以下参数
        if (request.getUpdateType() == 0) {
            if (request.getPeopleNum() == null || request.getMaxPurchase() == null || request.getMaxPurchase() == null || request.getJoinRegiment() == null) {
                return ResultModel.fail("请输入完整拼团参数配置~！");
            }
            if (request.getGoodSpecRequestList() == null) {
                return ResultModel.fail("请输入拼团金额和平台库存~！");
            }
        }

        // 查询商品信息
        GoodsModel goodsModel = goodsMapper.selectByPrimaryKey(request.getGoodsId());
        // 如果该商品是秒杀则抛出异常
        if (goodsModel.getIsKill() == 1) {
            return ResultModel.fail("该商品已经有秒杀配置~！");
        }


        GoodsAssembleModel model = new GoodsAssembleModel();
        BeanUtils.copyProperties(request, model);
        try {
            if (isNumber(request.getStartTimes())) {
                model.setStartTime(new Date(Long.parseLong(request.getStartTimes())));
                model.setEndTime(new Date(Long.parseLong(request.getEndTimes())));
            } else {
                model.setStartTime(formatter.parse(request.getStartTimes()));
                model.setEndTime(formatter.parse(request.getEndTimes()));
            }
        } catch (ParseException e) {
            log.error("插入商品拼团[异常]", e);
        }
        // 设置拼团有效期：如果当前拼团有效期不存在或者为0，则设置有效期为24小时
        if (model.getTermOfValidity() == null || model.getTermOfValidity() == 0) {
            model.setTermOfValidity(24);
        }

        boolean isSecKillGoods = isSecKillGoods(request.getGoodsId());
        if (isSecKillGoods) {
            return ResultModel.fail("该商品已经有秒杀配置~！");
        }
        // 保存商品平台配置
        boolean up = false;

        if (request.getAssembleId() != null) {
            goodsAssembleMapper.updateByPrimaryKeySelective(model);
            up = true;
        } else {
            GoodsAssembleModel goodsAssemble = goodsAssembleMapper.getGoodsAssemble(request.getGoodsId());
            if (goodsAssemble != null) {
                return ResultModel.fail("该商品已经有拼团配置~！");
            }
            model.setIsDel(0);
            model.setCreateTime(currentDate());
        }
        // 修改商品规格拼团配置
        if (null != request.getGoodSpecRequestList()) {
            for (GoodSpecRequest request1 : request.getGoodSpecRequestList()) {
                GoodSpecModel model1 = new GoodSpecModel();
                model1.setSpecId(request1.getSpecId());
                model1.setAssembleNum(request1.getAssembleNum());
                model1.setAssemblePrice(request1.getAssemblePrice());
                goodSpecMapper.updateByPrimaryKeySelective(model1);
            }
        }

        // 正式发布
        if (request.getAssembleType() == 1) {
            // 修改商品拼团状态
            goodsMapper.updateByPrimaryKeySelective(new GoodsModel() {{
                setGoodsId(request.getGoodsId());
                setIsAssemble(1);
                setAssembleTime(new Date());
            }});
            model.setState(1); // 状态为 进行中
        }

        if (!up) goodsAssembleMapper.insertSelective(model);
        return ResultModel.success(true);
    }

    private boolean isSecKillGoods(Integer goodsId) {
        SecKillModel secKillModel = secKillMapper.selectKillGoodsInfo(new SecKillModel() {{
            setIsDel(0);
            setState(1); // 秒杀进行中
            setGoodsId(goodsId);
        }});
        return secKillModel != null;
    }


    @Override
    public ResultModel<List<GoodsAssembleResponse>> selectGoodsAssembleDraftsPage(GoodsAssembleRequest request) {
        if (request == null || request.getCId() == null) {
            return ResultModel.checkParamFail("公司ID为空");
        }
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        GoodsAssembleModel model = new GoodsAssembleModel();
        model.setCompanyId(request.getCId().intValue());
        model.setAssembleType(request.getAssembleType());
        List<GoodsAssembleModel> list = goodsAssembleMapper.selectGoodsAssembleDraftsPage(model);
        if (list == null || list.size() <= 0) {
            return ResultModel.noData();
        }
        PageInfo<GoodsAssembleModel> pageInfo = new PageInfo<>(list);
        List<GoodsAssembleResponse> responseList = new ArrayList<>();
        // 进行中
        List<GoodsAssembleResponse> responseOneList = new ArrayList<>();
        // 已结束
        List<GoodsAssembleResponse> responseTwoList = new ArrayList<>();
        pageInfo.getList().forEach(obj -> {
            {
                GoodsAssembleResponse response = new GoodsAssembleResponse();
                BeanUtils.copyProperties(obj, response);
                // 判断拼团是否已结束(成团人数等于开团人数 或者 拼团结束时间大于等于当前时间) type 1：进行中 2：已结束
                if (response.getPeopleNum().equals(response.getPutAssemble()) || response.getEndTime().getTime() <= System.currentTimeMillis()) {
                    response.setType(2);
                    responseTwoList.add(response);
                } else {
                    response.setType(1);
                    responseOneList.add(response);
                }
                responseList.add(response);
            }
        });
        if (request.getRequestType() == 1) {
            // 进行中
            return ResultModel.success(responseOneList);
        } else if (request.getRequestType() == 2) {
            // 已结束
            return ResultModel.success(responseTwoList);
        } else {
            // 全部
            return ResultModel.success(responseList);
        }
    }

    @Override
    public ResultModel<Boolean> delGoodsAssembleInfo(GoodsAssembleRequest request) {
        if (request == null || request.getAssembleId() == null) {
            return ResultModel.checkParamFail("assembleId不能为空");
        }
        GoodsAssembleModel goodsAssembleModel = goodsAssembleMapper.selectByPrimaryKey(request.getAssembleId());
        if (goodsAssembleModel == null) {
            return ResultModel.success(true);
        }

        GoodsAssembleModel model = new GoodsAssembleModel();
        model.setAssembleId(request.getAssembleId());
        model.setIsDel(1);
        goodsAssembleMapper.updateByPrimaryKeySelective(model);
        // 取消商品拼团状态
        log.info("删除商品拼团活动: {}", request);
        goodsMapper.cancelAssembleActivities(goodsAssembleModel.getGoodsId());
        return ResultModel.success(true);
    }

    @Override
    public ResultModel<Boolean> releaseGoodsAssemble(GoodsAssembleRequest request) {
        if (request == null || request.getGoodsId() == null) {
            return ResultModel.checkParamFail("goodsId为空");
        }

        // 查询商品是否有秒杀状态
        GoodsModel goodsModel = goodsMapper.selectByPrimaryKey(request.getGoodsId());
        boolean isKill = (goodsModel.getIsKill() == 1);
        if (isKill) {
            return ResultModel.fail("该商品已有秒杀状态");
        } else {
            // 修改商品拼团状态
            goodsMapper.updateByPrimaryKeySelective(new GoodsModel() {{
                setGoodsId(request.getGoodsId());
                setIsAssemble(1);
                setAssembleTime(new Date());
            }});
            //修改商品拼团表状态
            goodsAssembleMapper.updateByPrimaryKeySelective(new GoodsAssembleModel() {{
                setAssembleId(request.getAssembleId());
                setAssembleType(1);
                setStart(1);
            }});
        }
        return ResultModel.success(true);
    }

    @Override
    public ResultModel<List<AssembleResponse>> selectGoodsAssemblePage(AssembleRequest request) {
        if (request == null || request.getCId() == null) {
            return ResultModel.checkParamFail("公司ID为空");
        }
        PageHelper.startPage(request.getPageNum(), request.getPageSize());
        AssembleModel model = new AssembleModel();
        BeanUtils.copyProperties(request, model);
        model.setCompanyId(request.getCId().intValue());
        List<AssembleModel> list = assembleMapper.selectGoodsAssemblePage(model);
        if (list == null || list.size() <= 0) {
            return ResultModel.noData();
        }
        PageInfo<AssembleModel> pageInfo = new PageInfo<>(list);
        List<AssembleResponse> responseList = new ArrayList<>();
        pageInfo.getList().forEach(obj -> {
            {
                AssembleResponse response = new AssembleResponse();
                BeanUtils.copyProperties(obj, response);
                response.setNickeName(getDecodeNickeName(response.getNickeName()));
                responseList.add(response);
            }
        });
        return ResultModel.success(responseList);
    }

    @Override
    public ResultModel<AssembleResponse> getGoodsAssembleInfo(AssembleRequest request) {
        if (request == null || request.getAssembleId() == null) {
            return ResultModel.checkParamFail("assembleId不能为空");
        }
        log.info("获取拼团详情请求：{}", JSON.toJSONString(request));
        AssembleModel model = new AssembleModel();
        model.setAssembleId(request.getAssembleId());
        List<AssembleModel> list = assembleMapper.selectGoodsAssemblePage(model);
        if (list == null || list.size() <= 0) {
            return ResultModel.noData();
        }
        AssembleResponse response = new AssembleResponse();
        BeanUtils.copyProperties(list.get(0), response);
        response.setNickeName(getDecodeNickeName(response.getNickeName()));

        response.setGoodSpecModelList(goodSpecMapper.getSpec(new GoodSpecModel() {{
            setGoodsId(response.getGoodsId());
        }}));

        List<AssembleModel> assembleModels = assembleMapper.ordersModelList(new AssembleModel() {{
            setAssembleId(request.getAssembleId());
        }});
        if (assembleModels != null) {
            assembleModels.forEach(a -> a.setNickeName(getDecodeNickeName(a.getNickeName())));
        }
        response.setOrdersModelList(assembleModels);

        log.info("获取拼团详情返回：{}", JSON.toJSONString(response));
        return ResultModel.success(response);
    }

    @Override
    public ResultModel<GoodsAssembleResponse> updateGoodsAssembleInfo(AssembleRequest request) {
        if (request == null || request.getAssembleId() == null) {
            return ResultModel.checkParamFail("assembleId不能为空");
        }
        GoodsAssembleModel model = new GoodsAssembleModel();
        model.setAssembleId(request.getAssembleId());
        List<GoodsAssembleModel> list = goodsAssembleMapper.selectGoodsAssemblePageUpdate(model);

        if (list == null || list.size() <= 0) {
            return ResultModel.noData();
        }
        GoodsAssembleResponse response = new GoodsAssembleResponse();
        BeanUtils.copyProperties(list.get(0), response);
        response.setTotalBuyNum(assembleMapper.selectCountBuyNum(new AssembleModel() {{
            setGoodsId(response.getGoodsId());
        }}));

        response.setGoodSpecModelList(goodSpecMapper.getSpec(new GoodSpecModel() {{
            setGoodsId(response.getGoodsId());
        }}));


        List<AssembleModel> assembleModels = assembleMapper.ordersModelList(new AssembleModel() {{
            setAssembleId(request.getAssembleId());
        }});
        if (assembleModels != null) {
            assembleModels.forEach(a -> a.setNickeName(getDecodeNickeName(a.getNickeName())));
        }

        response.setOrdersModelList(assembleModels);
        return ResultModel.success(response);
    }
}
